package com.moose.operator.web.service.impl.book;

import com.moose.operator.common.PageInfo;
import com.moose.operator.common.QueryWrapper;
import com.moose.operator.model.entity.HistoryBook;
import com.moose.operator.model.param.book.HistoryBookParam;
import com.moose.operator.web.service.HistoryBookService;
import java.util.List;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import org.bson.Document;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

/**
 * @author taohua
 */
@Service
public class HistoryBookServiceImpl implements HistoryBookService {

  @Resource
  private MongoTemplate mongoTemplate;

  @Override public PageInfo<HistoryBook> getHistoryBook(HistoryBookParam searchParam) {
    Integer pageNum = searchParam.getPageNum();
    Integer pageSize = searchParam.getPageSize();
    Long bookCategoryId = searchParam.getBookCategoryId();
    Aggregation aggregation = Aggregation.newAggregation(
        Aggregation.project(
            "book_id", "book_name", "dynasty", "author_name", "description", "book_category_id",
            "has_chapter_category"),
        Aggregation.match(Criteria.where("book_category_id").is(bookCategoryId)),
        QueryWrapper.buildSkipOperation(pageNum, pageSize),
        QueryWrapper.buildLimitOperation(pageSize));

    AggregationResults<Document> aggregate =
        mongoTemplate.aggregate(aggregation, "history_book", Document.class);

    List<Document> mappedResults = aggregate.getMappedResults();

    List<HistoryBook> historyBookCategoryList = mappedResults.stream().map(document -> {
      HistoryBook historyBook = new HistoryBook();
      historyBook.setAuthorName(document.getString("author_name"));
      historyBook.setBookName(document.getString("book_name"));
      historyBook.setBookId(document.getLong("book_id"));
      historyBook.setDynasty(document.getString("dynasty"));
      historyBook.setDescription(document.getString("description"));
      historyBook.setBookCategoryId(document.getLong("book_category_id"));
      historyBook.setHasChapterCategory(document.getInteger("has_chapter_category"));
      return historyBook;
    }).collect(Collectors.toList());

    // 计算当前类别下对应书籍总数
    Query query = QueryWrapper.buildQuery();
    query.addCriteria(Criteria.where("book_category_id").is(bookCategoryId));
    long totalSize = mongoTemplate.count(query, HistoryBook.class);
    PageInfo<HistoryBook> pageInfo = new PageInfo<>();
    pageInfo.setList(historyBookCategoryList);
    pageInfo.setPageSize(pageSize);
    pageInfo.setTotalSize(totalSize);
    pageInfo.setPageNum(pageNum);

    return pageInfo;
  }
}
